<?php
/**
 * Description: 获取看过但未评价过的课堂列表
 * User: devforma
 * Date: 15/12/31
 * Time: 12:33
 */

class GetUnratedClass implements iController {
    const PERPAGE_COUNT = 15; //每页显示数量

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (validateUser($queryArgs) !== 1 || empty($queryArgs['is_open']) || empty($queryArgs['page']) || !filter_var($queryArgs['page'], FILTER_VALIDATE_INT)) {
            return genOutput(1000);
        }

        $result = array();

        $offset = ($queryArgs['page'] - 1) * self::PERPAGE_COUNT;

        if ($queryArgs['is_open'] === 'true') {
            $sql = "SELECT `course_id`, `class_id` FROM `data_liveclass_grade` WHERE `user_id`=:uid AND `is_openclass`=1 AND `grade_score`=0
            ORDER BY `id` DESC LIMIT {$offset},".self::PERPAGE_COUNT;
        } else {
            $sql = "SELECT `course_id`, `class_id` FROM `data_liveclass_grade` WHERE `user_id`=:uid AND `is_openclass`=0 AND `grade_score`=0
            ORDER BY `id` DESC LIMIT {$offset},".self::PERPAGE_COUNT;
        }

        $ids = $cmsdb->getResults($sql, array(':uid' => $queryArgs['user_id']));
        if (!empty($ids)) {

            $classIds = array();
            $courseIds = array();
            foreach ($ids as $c) {
                $classIds[] = $c->class_id;
                $courseIds[] = $c->course_id;
            }

            $classIdStr = implode(',', $classIds);
            $sql = "SELECT c.id, c.class_name, c.start_time, c.end_time, t.name FROM `data_live_class` AS c, `data_teacher` AS t
            WHERE c.lector_id=t.id AND c.id IN ({$classIdStr}) ORDER BY FIELD (c.id, {$classIdStr})";
            $classes = $cmsdb->getResults($sql);

            $courseNames = $this->getCourseNames($courseIds);

            foreach ($classes as $index => $class) {
                $result[] = array(
                    'class_id' => intval($class->id),
                    'course_id' => intval($courseIds[$index]),
                    'course_name' => $courseNames[$ids[$index]->course_id],
                    'class_name' => $class->class_name,
                    'lector' => $class->name,
                    'start_time' => $class->start_time,
                    'end_time' => $class->end_time
                );
            }
        }

        return genOutput(1, array(
            'list' => $result
        ));
    }

    /**
     * 获取课程名称
     *
     * @param $courseIds
     * @return array
     */
    private function getCourseNames($courseIds) {
        global $cmsdb;

        $str = implode(',', $courseIds);

        $courses = $cmsdb->getResults("SELECT `id`, `course_name` FROM `data_live_course` WHERE `id` IN ({$str}) ORDER BY FIELD (`id`, {$str})");

        $list = array();
        foreach ($courses as $c) {
            $list[$c->id] = $c->course_name;
        }

        return $list;
    }
}